#include "Motor_Control_Panel.h"
#include "../Device_Motor/Device_Motor_FuYu.h"
#include "MotorConfig.h"
#include <QDebug>
#include <qelapsedtimer.h>
#include <QHBoxLayout>
#include <qinputdialog.h>
#include <QMessageBox>
#include <QScrollArea>
#include <QFile>
#include <QFileDialog>
#include <qfuture.h>
#include <QtConcurrent/qtconcurrentrun.h>
#include <QTimer>
#include <QDateTime>
#include <QThread>
#include <QCoreApplication>
#include <cmath>
#include <stdexcept>
#include "PositionConfigDialog.h"

Motor_Control_Panel::Motor_Control_Panel(QWidget *parent)
    : QDockWidget(parent,Qt::Window)
    , m_motor(nullptr)
{
    m_messageTimer = std::make_unique<QTimer>(this);
    m_statusMonitorTimer = std::make_unique<QTimer>(this);
    m_scanDataCollectionTimer = std::make_unique<QTimer>(this);

    m_beamQualityAnalysis = std::make_unique<BeamQualityAnalysis>(this);
    m_coordinateStrategy = std::make_unique<DefaultMotorStrategy>();

    // 初始化配置，尝试从文件加载
    MotorConfig* config = MotorConfig::getInstance();
    config->loadFromFile("config/motor_config.ini");

    // 设置状态监控定时器
    m_statusMonitorTimer->setInterval(100); // 每100ms检查一次状态
    connect(m_statusMonitorTimer.get(), &QTimer::timeout, this, &Motor_Control_Panel::onStatusMonitorTimer);
    connect(m_scanDataCollectionTimer.get(), &QTimer::timeout, this, &Motor_Control_Panel::onScanDataCollection);

    setupUI();
    updateUIState(false);
}

Motor_Control_Panel::~Motor_Control_Panel()
{
    if (m_motor && isMotorConnected()) {
        m_motor->Disconnect();
    }
    
    // 销毁配置单例
    MotorConfig::destroyInstance();
}

void Motor_Control_Panel::setupUI()
{
    setWindowTitle("电机控制测试程序");
    resize(1400, 800);

    // 创建滚动区域作为主容器
    QScrollArea *scrollArea = new QScrollArea(this);
    scrollArea->setWidgetResizable(true);
    scrollArea->setFrameShape(QFrame::NoFrame);
    scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);

    // 创建中央部件
    QWidget *centralWidget = new QWidget(scrollArea);
    centralWidget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);


    // 创建主布局
    QHBoxLayout *mainLayout = new QHBoxLayout(centralWidget);
    mainLayout->setContentsMargins(10, 10, 10, 10);
    mainLayout->setSpacing(15);

    // 创建左侧面板（基本控制）
    QWidget *leftPanel = new QWidget();
    leftPanel->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
    QVBoxLayout *leftLayout = new QVBoxLayout(leftPanel);
    leftLayout->setContentsMargins(5, 5, 5, 5);
    leftLayout->setSpacing(8);

    // 创建右侧面板（高级控制）
    QWidget *rightPanel = new QWidget();
    rightPanel->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
    QVBoxLayout *rightLayout = new QVBoxLayout(rightPanel);
    rightLayout->setContentsMargins(5, 5, 5, 5);
    rightLayout->setSpacing(8);
    // 创建分组框并设置统一的尺寸策略
    auto createGroupBox = [](const QString &title, QWidget *parent) {
        QGroupBox *group = new QGroupBox(title, parent);
        group->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
        group->setMinimumWidth(300); // 减小最小宽度以适应小屏幕
        return group;
    };

    // 左侧面板分组框
    QGroupBox *connectionGroup = createGroupBox("连接设置", leftPanel);
    setupConnectionGroup(connectionGroup);
    leftLayout->addWidget(connectionGroup, 0, Qt::AlignTop);

    QGroupBox *movementGroup = createGroupBox("移动控制", leftPanel);
    setupMovementGroup(movementGroup);
    leftLayout->addWidget(movementGroup, 0, Qt::AlignTop);

    QGroupBox *speedGroup = createGroupBox("速度设置", leftPanel);
    setupSpeedGroup(speedGroup);
    leftLayout->addWidget(speedGroup, 0, Qt::AlignTop);

    // 右侧面板分组框
    QGroupBox *interpolationGroup = createGroupBox("插补控制", rightPanel);
    setupInterpolationGroup(interpolationGroup);
    rightLayout->addWidget(interpolationGroup, 0, Qt::AlignTop);

    QGroupBox *ioGroup = createGroupBox("IO控制", rightPanel);
    setupIOGroup(ioGroup);
    rightLayout->addWidget(ioGroup, 0, Qt::AlignTop);

    QGroupBox *rs485Group = createGroupBox("485通信", rightPanel);
    setup485Group(rs485Group);
    rightLayout->addWidget(rs485Group, 0, Qt::AlignTop);


    QGroupBox *presetGroup = createGroupBox("预设位置管理", rightPanel);
    setupPresetGroup(presetGroup);
    rightLayout->insertWidget(0, presetGroup);

    // 添加拉伸因子使剩余空间均匀分布
    leftLayout->addStretch(1);
    rightLayout->addStretch(1);

    // 创建滚动区域包装左右面板
    QScrollArea *leftScrollArea = new QScrollArea();
    leftScrollArea->setWidgetResizable(true);
    leftScrollArea->setFrameShape(QFrame::NoFrame);
    leftScrollArea->setWidget(leftPanel);
    leftScrollArea->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);

    QScrollArea *rightScrollArea = new QScrollArea();
    rightScrollArea->setWidgetResizable(true);
    rightScrollArea->setFrameShape(QFrame::NoFrame);
    rightScrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    rightScrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    rightScrollArea->setWidget(rightPanel);
    rightScrollArea->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);

    // 添加左右面板到主布局，确保各占一半空间
    mainLayout->addWidget(leftScrollArea, 1); // 左侧占1份拉伸因子
    mainLayout->addWidget(rightScrollArea, 1); // 右侧占1份拉伸因子

    QVBoxLayout *statusLayout = new QVBoxLayout();

    // 创建包含位置、速度、状态的水平布局
    QHBoxLayout *statusInfoLayout = new QHBoxLayout();
    statusInfoLayout->setSpacing(15);

    // 位置信息
    QVBoxLayout *positionLayout = new QVBoxLayout();
    positionLayout->setSpacing(2);
    positionLayout->addWidget(new QLabel("位置:"), 0, Qt::AlignLeft);
    m_positionLabel = new QLabel("0.0");
    m_positionLabel->setFrameStyle(QFrame::Panel | QFrame::Sunken);
    m_positionLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    m_positionLabel->setMinimumWidth(80);
    positionLayout->addWidget(m_positionLabel, 0, Qt::AlignLeft);
    statusInfoLayout->addLayout(positionLayout);

    // 速度信息
    QVBoxLayout *speedLayout = new QVBoxLayout();
    speedLayout->setSpacing(2);
    speedLayout->addWidget(new QLabel("速度:"), 0, Qt::AlignLeft);
    m_speedLabel = new QLabel("0.0");
    m_speedLabel->setFrameStyle(QFrame::Panel | QFrame::Sunken);
    m_speedLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    m_speedLabel->setMinimumWidth(80);
    speedLayout->addWidget(m_speedLabel, 0, Qt::AlignLeft);
    statusInfoLayout->addLayout(speedLayout);

    // 状态信息
    QVBoxLayout *stateLayout = new QVBoxLayout();
    stateLayout->setSpacing(2);
    stateLayout->addWidget(new QLabel("状态:"), 0, Qt::AlignLeft);
    m_statusLabel = new QLabel("未连接");
    m_statusLabel->setFrameStyle(QFrame::Panel | QFrame::Sunken);
    m_statusLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    m_statusLabel->setMinimumWidth(100);
    stateLayout->addWidget(m_statusLabel, 0, Qt::AlignLeft);
    statusInfoLayout->addLayout(stateLayout);

    statusInfoLayout->addStretch();

    statusLayout->addLayout(statusInfoLayout);

    // 消息标签 - 修改为白色字体，更大尺寸
    m_messageLabel = new QLabel(this);
    m_messageLabel->setVisible(false);
    m_messageLabel->setStyleSheet("color: white; font-weight: bold; font-size: 14px;");
    m_messageLabel->setWordWrap(true);
    statusLayout->addWidget(m_messageLabel);

    leftLayout->addLayout(statusLayout);

    centralWidget->setLayout(mainLayout);
    m_messageTimer->setSingleShot(true);
    connect(m_messageTimer.get(), &QTimer::timeout, this, [this]() {
        m_messageLabel->setVisible(false);
    });

    // 设置滚动区域的内容部件
    scrollArea->setWidget(centralWidget);

    // 设置滚动区域为dock的主部件
    setWidget(scrollArea);

    // 设置最小尺寸以适应小屏幕
    setMinimumSize(800, 600);
}

void Motor_Control_Panel::setupConnectionGroup(QGroupBox *connectionGroup)
{
    QGridLayout *layout = new QGridLayout(connectionGroup);
    layout->setContentsMargins(12, 12, 12, 12);
    layout->setHorizontalSpacing(15);
    layout->setVerticalSpacing(10);

    // 第一行 - 电机类型
    layout->addWidget(new QLabel("电机类型:"), 0, 0);
    m_motorTypeComboBox = new QComboBox(this);
    m_motorTypeComboBox->addItem("默认电机", static_cast<int>(MotorType::Device_Motor_Default));
    m_motorTypeComboBox->addItem("FuYu电机", static_cast<int>(MotorType::Device_Motor_FuYu));
    m_motorTypeComboBox->setCurrentIndex(1);
    layout->addWidget(m_motorTypeComboBox, 0, 1, 1, 2);

    // 从配置获取默认值
    MotorConfig* config = MotorConfig::getInstance();

    // 第二行 - IP地址
    layout->addWidget(new QLabel("IP地址:"), 1, 0);
    m_ipAddressEdit = new QLineEdit(config->getDefaultIpAddress());
    layout->addWidget(m_ipAddressEdit, 1, 1, 1, 2);

    // 第三行 - 端口和设备ID
    layout->addWidget(new QLabel("端口:"), 2, 0);
    m_portSpinBox = new QSpinBox(this);
    m_portSpinBox->setRange(0, 65535);
    m_portSpinBox->setValue(config->getDefaultPort());
    layout->addWidget(m_portSpinBox, 2, 1);

    layout->addWidget(new QLabel("设备ID:"), 2, 2);
    m_deviceIdSpinBox = new QSpinBox(this);
    m_deviceIdSpinBox->setRange(0, 255);
    m_deviceIdSpinBox->setValue(config->getDefaultDeviceId());
    layout->addWidget(m_deviceIdSpinBox, 2, 3);

    // 第四行 - 轴号
    layout->addWidget(new QLabel("轴号:"), 3, 0);
    m_axisSpinBox = new QSpinBox(this);
    m_axisSpinBox->setRange(0, 7);
    m_axisSpinBox->setValue(config->getDefaultAxis());
    layout->addWidget(m_axisSpinBox, 3, 1, 1, 3);

    // 第五行 - 按钮
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    buttonLayout->setSpacing(20);
    m_connectButton = new QPushButton("连接");
    m_connectButton->setMinimumWidth(120);
    m_disconnectButton = new QPushButton("断开连接");
    m_disconnectButton->setMinimumWidth(120);
    buttonLayout->addWidget(m_connectButton);
    buttonLayout->addWidget(m_disconnectButton);
    layout->addLayout(buttonLayout, 4, 0, 1, 4);

    // 连接信号和槽
    connect(m_connectButton, &QPushButton::clicked, this, &Motor_Control_Panel::onConnectClicked);
    connect(m_disconnectButton, &QPushButton::clicked, this, &Motor_Control_Panel::onDisconnectClicked);
}

void Motor_Control_Panel::setupMovementGroup(QGroupBox *movementGroup)
{
    QGridLayout *layout = new QGridLayout(movementGroup);
    layout->setContentsMargins(12, 12, 12, 12);
    layout->setHorizontalSpacing(15);
    layout->setVerticalSpacing(10);

    // 绝对位置
    layout->addWidget(new QLabel("绝对位置:"), 0, 0);
    m_positionSpinBox = new QDoubleSpinBox();
    m_positionSpinBox->setRange(-1000000, 1000000);
    m_positionSpinBox->setDecimals(3);
    layout->addWidget(m_positionSpinBox, 0, 1, 1, 3);

    // 相对距离
    layout->addWidget(new QLabel("相对距离:"), 1, 0);
    m_relativeDistanceSpinBox = new QDoubleSpinBox();
    m_relativeDistanceSpinBox->setRange(-1000000, 1000000);
    m_relativeDistanceSpinBox->setDecimals(3);
    layout->addWidget(m_relativeDistanceSpinBox, 1, 1, 1, 3);

    // 运动模式
    layout->addWidget(new QLabel("运动模式:"), 2, 0);
    m_motionModeComboBox = new QComboBox();
    m_motionModeComboBox->addItem("绝对运动", static_cast<int>(MotionMode::Absolute));
    m_motionModeComboBox->addItem("相对运动", static_cast<int>(MotionMode::Relative));
    layout->addWidget(m_motionModeComboBox, 2, 1, 1, 3);

    // 回零方向
    layout->addWidget(new QLabel("回零方向:"), 3, 0);
    m_homeDirectionComboBox = new QComboBox();
    m_homeDirectionComboBox->addItem("正向", static_cast<int>(HomeDirection::Positive));
    m_homeDirectionComboBox->addItem("反向", static_cast<int>(HomeDirection::Negative));
    //默认反向
    m_homeDirectionComboBox->setCurrentIndex(1);
    layout->addWidget(m_homeDirectionComboBox, 3, 1, 1, 3);

    // 停止模式
    layout->addWidget(new QLabel("停止模式:"), 4, 0);
    m_stopModeComboBox = new QComboBox();
    m_stopModeComboBox->addItem("减速停止", static_cast<int>(StopMode::Decelerate));
    m_stopModeComboBox->addItem("立即停止", static_cast<int>(StopMode::Immediate));
    layout->addWidget(m_stopModeComboBox, 4, 1, 1, 3);

    // 移动按钮
    QHBoxLayout *moveButtonLayout = new QHBoxLayout();
    moveButtonLayout->setSpacing(20);
    m_moveToButton = new QPushButton("移动到位置");
    m_moveToButton->setMinimumWidth(120);
    m_moveRelativeButton = new QPushButton("相对移动");
    m_moveRelativeButton->setMinimumWidth(120);
    moveButtonLayout->addWidget(m_moveToButton);
    moveButtonLayout->addWidget(m_moveRelativeButton);
    layout->addLayout(moveButtonLayout, 5, 0, 1, 4);

    // 回零和停止按钮
    QHBoxLayout *homeStopButtonLayout = new QHBoxLayout();
    homeStopButtonLayout->setSpacing(20);
    m_homeButton = new QPushButton("回零");
    m_homeButton->setMinimumWidth(120);
    m_stopButton = new QPushButton("停止");
    m_stopButton->setMinimumWidth(120);
    homeStopButtonLayout->addWidget(m_homeButton);
    homeStopButtonLayout->addWidget(m_stopButton);
    layout->addLayout(homeStopButtonLayout, 6, 0, 1, 4);

    // 连接信号和槽
    connect(m_moveToButton, &QPushButton::clicked, this, &Motor_Control_Panel::onMoveToClicked);
    connect(m_moveRelativeButton, &QPushButton::clicked, this, &Motor_Control_Panel::onMoveRelativeClicked);
    connect(m_homeButton, &QPushButton::clicked, this, &Motor_Control_Panel::onHomeClicked);
    connect(m_stopButton, &QPushButton::clicked, this, &Motor_Control_Panel::onStopClicked);
}

void Motor_Control_Panel::setupSpeedGroup(QGroupBox *speedGroup)
{
    QGridLayout *layout = new QGridLayout(speedGroup);
    layout->setContentsMargins(12, 12, 12, 12);
    layout->setHorizontalSpacing(15);
    layout->setVerticalSpacing(10);

    // 速度设置
    QLabel* speedLabel = new QLabel("速度:");
    QLabel* speedUnit = new QLabel("(mm/s)");
    QHBoxLayout* speedLabelLayout = new QHBoxLayout();
    speedLabelLayout->addWidget(speedLabel);
    speedLabelLayout->addWidget(speedUnit);
    speedLabelLayout->addStretch();
    layout->addLayout(speedLabelLayout, 0, 0);

    // 从配置获取默认值
    MotorConfig* config = MotorConfig::getInstance();

    m_speedSpinBox = new QDoubleSpinBox();
    m_speedSpinBox->setRange(0, 100000);
    m_speedSpinBox->setValue(config->getDefaultSpeed());
    m_speedSpinBox->setDecimals(3);
    m_speedSpinBox->setToolTip("设置电机运动速度 (mm/s)");
    layout->addWidget(m_speedSpinBox, 0, 1);
    m_setSpeedButton = new QPushButton("设置速度");
    m_setSpeedButton->setMinimumWidth(120);
    layout->addWidget(m_setSpeedButton, 0, 2);

    // 加速度设置
    QLabel* accelLabel = new QLabel("加速度:");
    QLabel* accelUnit = new QLabel("(mm/s²)");
    QHBoxLayout* accelLabelLayout = new QHBoxLayout();
    accelLabelLayout->addWidget(accelLabel);
    accelLabelLayout->addWidget(accelUnit);
    accelLabelLayout->addStretch();
    layout->addLayout(accelLabelLayout, 1, 0);

    m_accelerationSpinBox = new QDoubleSpinBox();
    m_accelerationSpinBox->setRange(0, 100000);
    m_accelerationSpinBox->setValue(config->getDefaultAcceleration());
    m_accelerationSpinBox->setDecimals(3);
    m_accelerationSpinBox->setToolTip("设置电机加速度 (mm/s²)");
    layout->addWidget(m_accelerationSpinBox, 1, 1);
    m_setAccelerationButton = new QPushButton("设置加速度");
    m_setAccelerationButton->setMinimumWidth(120);
    layout->addWidget(m_setAccelerationButton, 1, 2);

    // 减速度设置
    QLabel* decelLabel = new QLabel("减速度:");
    QLabel* decelUnit = new QLabel("(mm/s²)");
    QHBoxLayout* decelLabelLayout = new QHBoxLayout();
    decelLabelLayout->addWidget(decelLabel);
    decelLabelLayout->addWidget(decelUnit);
    decelLabelLayout->addStretch();
    layout->addLayout(decelLabelLayout, 2, 0);

    m_decelerationSpinBox = new QDoubleSpinBox();
    m_decelerationSpinBox->setRange(0, 100000);
    m_decelerationSpinBox->setValue(config->getDefaultDeceleration());
    m_decelerationSpinBox->setDecimals(3);
    m_decelerationSpinBox->setToolTip("设置电机减速度 (mm/s²)");
    layout->addWidget(m_decelerationSpinBox, 2, 1);
    m_setDecelerationButton = new QPushButton("设置减速度");
    m_setDecelerationButton->setMinimumWidth(120);
    layout->addWidget(m_setDecelerationButton, 2, 2);

    // 回零参数设置标题
    QLabel* homeParamsLabel = new QLabel("回零参数:");
    layout->addWidget(homeParamsLabel, 3, 0, 1, 3, Qt::AlignLeft);

    // 回零速度设置
    QLabel* homeSpeedLabel = new QLabel("回零速度:");
    QLabel* homeSpeedUnit = new QLabel("(mm/s)");
    QHBoxLayout* homeSpeedLabelLayout = new QHBoxLayout();
    homeSpeedLabelLayout->addWidget(homeSpeedLabel);
    homeSpeedLabelLayout->addWidget(homeSpeedUnit);
    homeSpeedLabelLayout->addStretch();
    layout->addLayout(homeSpeedLabelLayout, 4, 0);

    m_homeSpeedSpinBox = new QDoubleSpinBox();
    m_homeSpeedSpinBox->setRange(0, 100000);
    m_homeSpeedSpinBox->setValue(config->getHomeSpeed());
    m_homeSpeedSpinBox->setDecimals(3);
    m_homeSpeedSpinBox->setToolTip("设置电机回零速度 (mm/s)");
    layout->addWidget(m_homeSpeedSpinBox, 4, 1);

    // 回零加减速度设置
    QLabel* homeAccDecLabel = new QLabel("回零加减速度:");
    QLabel* homeAccDecUnit = new QLabel("(mm/s²)");
    QHBoxLayout* homeAccDecLabelLayout = new QHBoxLayout();
    homeAccDecLabelLayout->addWidget(homeAccDecLabel);
    homeAccDecLabelLayout->addWidget(homeAccDecUnit);
    homeAccDecLabelLayout->addStretch();
    layout->addLayout(homeAccDecLabelLayout, 5, 0);

    m_homeAccDecSpinBox = new QDoubleSpinBox();
    m_homeAccDecSpinBox->setRange(0, 100000);
    m_homeAccDecSpinBox->setValue(config->getHomeAccDec());
    m_homeAccDecSpinBox->setDecimals(3);
    m_homeAccDecSpinBox->setToolTip("设置电机回零加减速度 (mm/s²)");
    layout->addWidget(m_homeAccDecSpinBox, 5, 1);

    // 回零脱落距离设置
    QLabel* homeFallStepLabel = new QLabel("脱落距离:");
    QLabel* homeFallStepUnit = new QLabel("(mm)");
    QHBoxLayout* homeFallStepLabelLayout = new QHBoxLayout();
    homeFallStepLabelLayout->addWidget(homeFallStepLabel);
    homeFallStepLabelLayout->addWidget(homeFallStepUnit);
    homeFallStepLabelLayout->addStretch();
    layout->addLayout(homeFallStepLabelLayout, 6, 0);

    m_homeFallStepSpinBox = new QDoubleSpinBox();
    m_homeFallStepSpinBox->setRange(0, 100000);
    m_homeFallStepSpinBox->setValue(config->getHomeFallStep());
    m_homeFallStepSpinBox->setDecimals(3);
    m_homeFallStepSpinBox->setToolTip("设置回零完成后远离限位开关的距离 (mm)");
    layout->addWidget(m_homeFallStepSpinBox, 6, 1);

    // 设置回零参数按钮
    QPushButton* m_setHomeParamsButton = new QPushButton("设置回零参数");
    m_setHomeParamsButton->setMinimumWidth(120);
    layout->addWidget(m_setHomeParamsButton, 4, 2, 3, 1); // 跨3行

    // 连接信号和槽
    connect(m_setSpeedButton, &QPushButton::clicked, this, &Motor_Control_Panel::onSetSpeedClicked);
    connect(m_setAccelerationButton, &QPushButton::clicked, this, &Motor_Control_Panel::onSetAccelerationClicked);
    connect(m_setDecelerationButton, &QPushButton::clicked, this, &Motor_Control_Panel::onSetDecelerationClicked);
    connect(m_setHomeParamsButton, &QPushButton::clicked, this, &Motor_Control_Panel::onSetHomeParameters);
}

void Motor_Control_Panel::setupInterpolationGroup(QGroupBox *interpolationGroup)
{
    QGridLayout *layout = new QGridLayout(interpolationGroup);
    layout->setContentsMargins(12, 12, 12, 12);
    layout->setHorizontalSpacing(15);
    layout->setVerticalSpacing(10);

    // 2轴线性插补
    layout->addWidget(new QLabel("2轴线性插补:"), 0, 0);

    QHBoxLayout *axis2Layout = new QHBoxLayout();
    axis2Layout->setSpacing(10);
    axis2Layout->addWidget(new QLabel("X(mm):"));
    m_x2AxisSpinBox = new QDoubleSpinBox();
    m_x2AxisSpinBox->setRange(-1000000, 1000000);
    m_x2AxisSpinBox->setDecimals(3);
    axis2Layout->addWidget(m_x2AxisSpinBox);

    axis2Layout->addWidget(new QLabel("Y(mm):"));
    m_y2AxisSpinBox = new QDoubleSpinBox();
    m_y2AxisSpinBox->setRange(-1000000, 1000000);
    m_y2AxisSpinBox->setDecimals(3);
    axis2Layout->addWidget(m_y2AxisSpinBox);

    layout->addLayout(axis2Layout, 0, 1);

    m_linearInterpolation2AxisButton = new QPushButton("执行2轴插补");
    m_linearInterpolation2AxisButton->setMinimumWidth(120);
    layout->addWidget(m_linearInterpolation2AxisButton, 0, 2);

    // 3轴线性插补
    layout->addWidget(new QLabel("3轴线性插补:"), 1, 0);

    QHBoxLayout *axis3Layout = new QHBoxLayout();
    axis3Layout->setSpacing(10);
    axis3Layout->addWidget(new QLabel("X(mm):"));
    m_x3AxisSpinBox = new QDoubleSpinBox();
    m_x3AxisSpinBox->setRange(-1000000, 1000000);
    m_x3AxisSpinBox->setDecimals(3);
    axis3Layout->addWidget(m_x3AxisSpinBox);

    axis3Layout->addWidget(new QLabel("Y(mm):"));
    m_y3AxisSpinBox = new QDoubleSpinBox();
    m_y3AxisSpinBox->setRange(-1000000, 1000000);
    m_y3AxisSpinBox->setDecimals(3);
    axis3Layout->addWidget(m_y3AxisSpinBox);

    axis3Layout->addWidget(new QLabel("Z(mm):"));
    m_z3AxisSpinBox = new QDoubleSpinBox();
    m_z3AxisSpinBox->setRange(-1000000, 1000000);
    m_z3AxisSpinBox->setDecimals(3);
    axis3Layout->addWidget(m_z3AxisSpinBox);

    layout->addLayout(axis3Layout, 1, 1);

    m_linearInterpolation3AxisButton = new QPushButton("执行3轴插补");
    m_linearInterpolation3AxisButton->setMinimumWidth(120);
    layout->addWidget(m_linearInterpolation3AxisButton, 1, 2);

    // 圆弧插补
    layout->addWidget(new QLabel("圆弧插补:"), 2, 0);

    QHBoxLayout *arcLayout = new QHBoxLayout();
    arcLayout->setSpacing(10);
    arcLayout->addWidget(new QLabel("X(mm):"));
    m_xArcSpinBox = new QDoubleSpinBox();
    m_xArcSpinBox->setRange(-1000000, 1000000);
    m_xArcSpinBox->setDecimals(3);
    arcLayout->addWidget(m_xArcSpinBox);

    arcLayout->addWidget(new QLabel("Y(mm):"));
    m_yArcSpinBox = new QDoubleSpinBox();
    m_yArcSpinBox->setRange(-1000000, 1000000);
    m_yArcSpinBox->setDecimals(3);
    arcLayout->addWidget(m_yArcSpinBox);

    arcLayout->addWidget(new QLabel("角度(°):"));
    m_angleArcSpinBox = new QDoubleSpinBox();
    m_angleArcSpinBox->setRange(-360, 360);
    m_angleArcSpinBox->setDecimals(3);
    arcLayout->addWidget(m_angleArcSpinBox);

    layout->addLayout(arcLayout, 2, 1);

    m_arcInterpolationButton = new QPushButton("执行圆弧插补");
    m_arcInterpolationButton->setMinimumWidth(120);
    layout->addWidget(m_arcInterpolationButton, 2, 2);

    // 停止插补
    m_stopInterpolationButton = new QPushButton("停止所有插补");
    m_stopInterpolationButton->setMinimumWidth(120);
    layout->addWidget(m_stopInterpolationButton, 3, 0, 1, 3);

    // 连接信号和槽



}

void Motor_Control_Panel::setupIOGroup(QGroupBox *ioGroup)
{
    QGridLayout *layout = new QGridLayout(ioGroup);
    layout->setContentsMargins(12, 12, 12, 12);
    layout->setHorizontalSpacing(15);
    layout->setVerticalSpacing(10);

    // 输出控制
    layout->addWidget(new QLabel("输出端口:"), 0, 0);
    m_outputPortSpinBox = new QSpinBox();
    m_outputPortSpinBox->setRange(0, 31);
    layout->addWidget(m_outputPortSpinBox, 0, 1);

    layout->addWidget(new QLabel("输出值:"), 0, 2);
    m_outputValueSpinBox = new QSpinBox();
    m_outputValueSpinBox->setRange(0, 1);
    layout->addWidget(m_outputValueSpinBox, 0, 3);

    m_setOutputButton = new QPushButton("设置输出");
    m_setOutputButton->setMinimumWidth(120);
    layout->addWidget(m_setOutputButton, 0, 4);

    // 输入控制
    layout->addWidget(new QLabel("输入端口:"), 1, 0);
    m_inputPortSpinBox = new QSpinBox();
    m_inputPortSpinBox->setRange(0, 31);
    layout->addWidget(m_inputPortSpinBox, 1, 1);

    layout->addWidget(new QLabel("输入状态:"), 1, 2);
    m_inputValueLabel = new QLabel("未读取");
    m_inputValueLabel->setFrameStyle(QFrame::Panel | QFrame::Sunken);
    m_inputValueLabel->setAlignment(Qt::AlignCenter);
    layout->addWidget(m_inputValueLabel, 1, 3);

    m_getInputButton = new QPushButton("获取输入");
    m_getInputButton->setMinimumWidth(120);
    layout->addWidget(m_getInputButton, 1, 4);

    // 连接信号和槽


}

void Motor_Control_Panel::setup485Group(QGroupBox *rs485Group)
{
    QGridLayout *layout = new QGridLayout(rs485Group);
    layout->setContentsMargins(12, 12, 12, 12);
    layout->setHorizontalSpacing(15);
    layout->setVerticalSpacing(10);

    // 写入数据
    layout->addWidget(new QLabel("发送数据:"), 0, 0);
    m_write485DataEdit = new QLineEdit();
    m_write485DataEdit->setPlaceholderText("输入要发送的数据");
    layout->addWidget(m_write485DataEdit, 0, 1, 1, 2);

    m_write485DataButton = new QPushButton("发送");
    m_write485DataButton->setMinimumWidth(120);
    layout->addWidget(m_write485DataButton, 0, 3);

    // 读取数据
    layout->addWidget(new QLabel("接收数据:"), 1, 0);
    m_read485DataEdit = new QLineEdit();
    m_read485DataEdit->setReadOnly(true);
    m_read485DataEdit->setPlaceholderText("接收到的数据显示在这里");
    layout->addWidget(m_read485DataEdit, 1, 1, 1, 2);

    m_read485DataButton = new QPushButton("接收");
    m_read485DataButton->setMinimumWidth(120);
    layout->addWidget(m_read485DataButton, 1, 3);

    // 连接信号和槽


}

void Motor_Control_Panel::setupPresetGroup(QGroupBox *group)
{
    QVBoxLayout *layout = new QVBoxLayout(group);
    layout->setContentsMargins(10, 10, 10, 10);
    layout->setSpacing(8);

    // 创建位置列表显示
    QLabel *listLabel = new QLabel("预设位置列表:", this);
    layout->addWidget(listLabel);
    
    m_presetListWidget = new QListWidget(this);
    m_presetListWidget->setMaximumHeight(150);
    m_presetListWidget->setSelectionMode(QAbstractItemView::SingleSelection);
    layout->addWidget(m_presetListWidget);

    // 创建按钮布局
    QHBoxLayout *buttonLayout1 = new QHBoxLayout();
    buttonLayout1->setSpacing(10);
    
    m_configurePositionButton = new QPushButton("📝 配置位置", this);
    m_configurePositionButton->setMinimumHeight(35);
    m_configurePositionButton->setToolTip("打开位置配置对话框，添加、删除、排序位置");
    
    m_moveToPresetButton = new QPushButton("➤ 移动到", this);
    m_moveToPresetButton->setMinimumHeight(35);
    m_moveToPresetButton->setEnabled(false);
    m_moveToPresetButton->setToolTip("移动到选中的预设位置");
    
    buttonLayout1->addWidget(m_configurePositionButton);
    buttonLayout1->addWidget(m_moveToPresetButton);
    layout->addLayout(buttonLayout1);

    // 第二行按钮
    QHBoxLayout *buttonLayout2 = new QHBoxLayout();
    buttonLayout2->setSpacing(10);
    
    m_sequentialMoveButton = new QPushButton("🔄 顺序移动", this);
    m_sequentialMoveButton->setMinimumHeight(35);
    m_sequentialMoveButton->setEnabled(false);
    m_sequentialMoveButton->setToolTip("按顺序移动到所有预设位置");
    
    m_measurementModeCheckBox = new QCheckBox("测量模式", this);
    m_measurementModeCheckBox->setToolTip("启用后将在每个位置进行测量");
    
    buttonLayout2->addWidget(m_sequentialMoveButton);
    buttonLayout2->addWidget(m_measurementModeCheckBox);
    layout->addLayout(buttonLayout2);

    // 连接信号和槽
    connect(m_configurePositionButton, &QPushButton::clicked, 
            this, &Motor_Control_Panel::onConfigurePositionClicked);
    connect(m_moveToPresetButton, &QPushButton::clicked, 
            this, &Motor_Control_Panel::onMoveToPresetClicked);
    connect(m_sequentialMoveButton, &QPushButton::clicked, 
            this, &Motor_Control_Panel::onSequentialMoveClicked);
    connect(m_presetListWidget, &QListWidget::itemSelectionChanged,
            this, &Motor_Control_Panel::onPresetSelectionChanged);
    connect(m_presetListWidget, &QListWidget::itemDoubleClicked,
            this, &Motor_Control_Panel::onPresetDoubleClicked);
}

void Motor_Control_Panel::updateUIState(bool connected)
{
    // 连接设置
    m_motorTypeComboBox->setEnabled(!connected);
    m_ipAddressEdit->setEnabled(!connected);
    m_portSpinBox->setEnabled(!connected);
    m_deviceIdSpinBox->setEnabled(!connected);
    m_axisSpinBox->setEnabled(!connected);
    m_connectButton->setEnabled(!connected);
    m_disconnectButton->setEnabled(connected);

    // 移动控制
    m_positionSpinBox->setEnabled(connected);
    m_relativeDistanceSpinBox->setEnabled(connected);
    m_motionModeComboBox->setEnabled(connected);
    m_moveToButton->setEnabled(connected);
    m_moveRelativeButton->setEnabled(connected);
    m_homeButton->setEnabled(connected);
    m_stopButton->setEnabled(connected);
    m_homeDirectionComboBox->setEnabled(connected);
    m_stopModeComboBox->setEnabled(connected);

    // 速度和加速度设置
    m_speedSpinBox->setEnabled(connected);
    m_accelerationSpinBox->setEnabled(connected);
    m_decelerationSpinBox->setEnabled(connected);
    m_setSpeedButton->setEnabled(connected);
    m_setAccelerationButton->setEnabled(connected);
    m_setDecelerationButton->setEnabled(connected);

    // 插补控制
    m_x2AxisSpinBox->setEnabled(connected);
    m_y2AxisSpinBox->setEnabled(connected);
    m_x3AxisSpinBox->setEnabled(connected);
    m_y3AxisSpinBox->setEnabled(connected);
    m_z3AxisSpinBox->setEnabled(connected);
    m_xArcSpinBox->setEnabled(connected);
    m_yArcSpinBox->setEnabled(connected);
    m_angleArcSpinBox->setEnabled(connected);
    m_linearInterpolation2AxisButton->setEnabled(connected);
    m_linearInterpolation3AxisButton->setEnabled(connected);
    m_arcInterpolationButton->setEnabled(connected);
    m_stopInterpolationButton->setEnabled(connected);

    // IO控制
    m_outputPortSpinBox->setEnabled(connected);
    m_outputValueSpinBox->setEnabled(connected);
    m_inputPortSpinBox->setEnabled(connected);
    m_setOutputButton->setEnabled(connected);
    m_getInputButton->setEnabled(connected);

    // 485通信
    m_write485DataEdit->setEnabled(connected);
    m_read485DataEdit->setEnabled(connected);
    m_write485DataButton->setEnabled(connected);
    m_read485DataButton->setEnabled(connected);
    
    // 预设位置管理
    m_configurePositionButton->setEnabled(true);  // 配置按钮始终可用
    m_moveToPresetButton->setEnabled(connected && m_presetListWidget->currentItem() != nullptr);
    m_sequentialMoveButton->setEnabled(connected && !m_presetPositions.isEmpty());

    updateStatus();
}

void Motor_Control_Panel::showMessage(const QString &message)
{
    m_messageLabel->setText(message);
    m_messageLabel->setVisible(true);
    m_messageTimer->start(3000); // 3秒后自动隐藏
    qDebug() << message;
}

void Motor_Control_Panel::updateStatus() {
    try {
        if (m_motor) {
            // 统一使用Device_Motor接口
            double internalPosition = m_motor->GetPosition();
            double externalPosition = m_coordinateStrategy->internalToExternal(internalPosition);
            double speed = m_motor->GetSpeed();
            MotorStatus status = m_motor->GetStatus();
                
            m_positionLabel->setText(QString::number(externalPosition, 'f', 3));
           emit positionUpdated(externalPosition);
            m_speedLabel->setText(QString::number(speed, 'f', 3));
                
            switch (status) {
                case MotorStatus::Connected:
                    m_statusLabel->setText(m_motor->IsMoving() ? "运动中" : "已连接");
                    break;
                case MotorStatus::Error:
                    m_statusLabel->setText("错误");
                    break;
                case MotorStatus::Moving:
                    m_statusLabel->setText("运动中");
                    break;
                case MotorStatus::Homing:
                    m_statusLabel->setText("回零中");
                    break;
                case MotorStatus::Stopped:
                    m_statusLabel->setText("已停止");
                    break;
                case MotorStatus::Disconnected:
                    m_statusLabel->setText("未连接");
                    break;
                default:
                    m_statusLabel->setText("未知");
            }
        } else {
            // 无连接状态
            m_positionLabel->setText("0.0");
            m_speedLabel->setText("0.0");
            m_statusLabel->setText("未连接");
        }
    } catch (...) {
        m_positionLabel->setText("读取错误");
        m_speedLabel->setText("读取错误");
        m_statusLabel->setText("错误");
    }
}

void Motor_Control_Panel::Motorstop()
{
    if (m_motor && isMotorConnected()) {
        m_motor->Stop(StopMode::Decelerate);
    }
}

bool Motor_Control_Panel::HasPresetPosition() const
{
    return !m_presetPositions.isEmpty();
}

void Motor_Control_Panel::ShowPresetWidget()
{
    onConfigurePositionClicked();
    qDebug() << "ShowPresetWidget called, using PositionConfigDialog";
}

void Motor_Control_Panel::MotorHome() {
    onHomeClicked();
}

void Motor_Control_Panel::MotorConnect() {
    onConnectClicked();
}

void Motor_Control_Panel::onConnectClicked()
{
    MotorType motorType = static_cast<MotorType>(m_motorTypeComboBox->currentData().toInt());
    QString ipAddress = m_ipAddressEdit->text();
    int port = m_portSpinBox->value();
    int deviceId = m_deviceIdSpinBox->value();
    int axis = m_axisSpinBox->value();

    // 重置现有连接
    if (m_motor) {
        m_motor.reset();
    }
    
    // 通过工厂创建电机（统一接口）
    m_motor = Device_Motor_Factory::instance().createMotor(motorType, this);
    if (!m_motor) {
        QMessageBox::critical(this, "错误", "创建电机设备失败");
        return;
    }

    // 如果是FuYu电机，设置特有参数
    if (motorType == MotorType::Device_Motor_FuYu) {
        auto fuyuMotor = std::dynamic_pointer_cast<Device_Motor_FuYu>(m_motor);
        if (fuyuMotor) {
            fuyuMotor->SetDeviceId(deviceId);
            fuyuMotor->SetIPAddress(ipAddress);
            fuyuMotor->setPort(port);
            fuyuMotor->SetAxis(axis);
        }
        m_coordinateStrategy = std::make_unique<FuYuMotorStrategy>(true);
    } else {
        m_coordinateStrategy = std::make_unique<DefaultMotorStrategy>();
    }

    // 设置运动参数
    double speed = m_speedSpinBox->value();
    double acceleration = m_accelerationSpinBox->value();
    double deceleration = m_decelerationSpinBox->value();
    m_motor->SetSpeed(speed);
    m_motor->SetAcceleration(acceleration);
    m_motor->SetDeceleration(deceleration);
    
    // 连接信号槽
    connect(m_motor.get(), &Device_Motor::OperationCompleted, this, [this](const QString& message) {
        showMessage(message);
    });

    // 连接设备
    if (!m_motor->Connect()) {
        QMessageBox::critical(this, "错误", "连接电机设备失败");
        m_motor = nullptr;
        return;
    }
    
    // 启动状态监控
    startStatusMonitoring();
    
    // 更新UI状态
    updateUIState(true);
    showMessage(QString("已连接到%1电机设备")
        .arg(motorType == MotorType::Device_Motor_FuYu ? "FuYu" : "通用"));
    
    // 如果是FuYu电机，禁用不支持的功能
    if (motorType == MotorType::Device_Motor_FuYu) {
        disableUnsupportedFeatures();
    }
}

void Motor_Control_Panel::onDisconnectClicked()
{
    if (m_motor) {
        stopStatusMonitoring();  // 停止状态监控
        m_motor->Disconnect();
        m_motor = nullptr;
    }
    
    updateUIState(false);
    m_connectButton->setEnabled(true);
    showMessage("已断开与电机设备的连接");
}

void Motor_Control_Panel::MoveAbsolute(double absolute) {
    // 检查电机连接状态
    if (!isMotorConnected()) {
        QMessageBox::warning(this, "警告", "电机设备未连接");
        return;
    }
    
    double externalPosition = 0;
    if (absolute == 0) {
        externalPosition = m_positionSpinBox->value();
    } else {
        m_positionSpinBox->setValue(absolute);
        externalPosition = absolute;
    }
    
    if (!m_coordinateStrategy->isValidExternalPosition(externalPosition, false)) {
        QMessageBox::warning(this, "无效位置",
                            m_coordinateStrategy->getInvalidPositionMessage(false));
        return;
    }

    double internalPosition = m_coordinateStrategy->externalToInternal(externalPosition, false);
    double speed = m_speedSpinBox->value();
    double acceleration = m_accelerationSpinBox->value();
    double deceleration = m_decelerationSpinBox->value();
    
    // 统一使用Device_Motor接口
    double currentPosition = m_motor->GetPosition();
    double distance = qAbs(internalPosition - currentPosition);
    m_motor->SetSpeed(speed);
    m_motor->SetAcceleration(acceleration);
    m_motor->SetDeceleration(deceleration);

    if (!m_motor->MoveTo(internalPosition, MotionMode::Absolute)) {
        QMessageBox::critical(this, "错误", "移动到指定位置失败");
        return;
    }

    double moveTime = calculateMoveTime(qAbs(internalPosition), speed, acceleration, deceleration);
    showMessage(QString("正在移动到位置: %1，预计需要 %2 秒").arg(externalPosition).arg(moveTime, 0, 'f', 2));
}

void Motor_Control_Panel::onMoveToClicked() {
    MoveAbsolute();
}

void Motor_Control_Panel::MoveRelative(double relative) {
    // 检查电机连接状态
    if (!isMotorConnected()) {
        QMessageBox::warning(this, "警告", "电机设备未连接");
        return;
    }
    
    double relativeDistance = 0;
    if (relative == 0) {
        relativeDistance = m_relativeDistanceSpinBox->value();
    } else {
        m_relativeDistanceSpinBox->setValue(relative);
        relativeDistance = relative;
    }

    double internalRelative = m_coordinateStrategy->externalToInternal(relativeDistance, true);
    double speed = m_speedSpinBox->value();
    double acceleration = m_accelerationSpinBox->value();
    double deceleration = m_decelerationSpinBox->value();

    // 统一使用Device_Motor接口
    m_motor->SetSpeed(speed);
    m_motor->SetAcceleration(acceleration);
    m_motor->SetDeceleration(deceleration);
        
    if (!m_motor->MoveTo(internalRelative, MotionMode::Relative)) {
        QMessageBox::critical(this, "错误", "相对移动失败");
        return;
    }
    
    double moveTime = calculateMoveTime(qAbs(internalRelative), speed, acceleration, deceleration);
    showMessage(QString("正在相对移动: %1，预计需要 %2 秒").arg(relativeDistance).arg(moveTime, 0, 'f', 2));
}

void Motor_Control_Panel::onMoveRelativeClicked() {
    MoveRelative();
}

void Motor_Control_Panel::onHomeClicked()
{
    // 检查电机连接状态
    if (!isMotorConnected()) {
        QMessageBox::warning(this, "警告", "电机设备未连接");
        return;
    }

    HomeDirection direction = static_cast<HomeDirection>(m_homeDirectionComboBox->currentData().toInt());

    // 统一使用Device_Motor接口（异步启动回零）
    if (!m_motor->Home(direction)) {
        QMessageBox::critical(this, "错误", "回零失败");
        return;
    }

    // 设置坐标系配置
    bool isPositiveMode = (direction == HomeDirection::Positive);
    m_coordinateStrategy->setPositiveMode(isPositiveMode);
    
    showMessage("正在回零，请等待电机停止...");
}

void Motor_Control_Panel::onStopClicked()
{
    // 检查连接状态（停止操作在任何连接状态下都可以执行）
    if (!isMotorConnected()) {
        QMessageBox::warning(this, "警告", "电机设备未连接");
        return;
    }

    StopMode stopMode = static_cast<StopMode>(m_stopModeComboBox->currentData().toInt());

    // 统一使用Device_Motor接口
    if (!m_motor->Stop(stopMode)) {
        QMessageBox::critical(this, "错误", "停止失败");
        return;
    }

    showMessage("已停止");
}

bool Motor_Control_Panel::isMotorConnected() const {
    if (!m_motor) {
        return false;
    }
    
    MotorStatus status = m_motor->GetStatus();
    // 电机在以下状态时都被认为是连接的
    return status == MotorStatus::Connected || 
           status == MotorStatus::Moving || 
           status == MotorStatus::Stopped || 
           status == MotorStatus::Homing;
}

bool Motor_Control_Panel::isMotorReadyForOperation() const {
    return isMotorConnected();
}

void Motor_Control_Panel::onSetSpeedClicked()
{
    if (!isMotorConnected()) {
        QMessageBox::warning(this, "警告", "电机设备未连接");
        return;
    }

    // 获取参数
    double speed = m_speedSpinBox->value();

    // 设置速度
    if (!m_motor->SetSpeed(speed)) {
        QMessageBox::critical(this, "错误", "设置速度失败");
        return;
    }

    showMessage(QString("已设置速度: %1").arg(speed));
}

void Motor_Control_Panel::onSetAccelerationClicked()
{
    if (!isMotorConnected()) {
        QMessageBox::warning(this, "警告", "电机设备未连接");
        return;
    }

    // 获取参数
    double acceleration = m_accelerationSpinBox->value();

    // 设置加速度
    if (!m_motor->SetAcceleration(acceleration)) {
        QMessageBox::critical(this, "错误", "设置加速度失败");
        return;
    }

    showMessage(QString("已设置加速度: %1").arg(acceleration));
}

void Motor_Control_Panel::onSetDecelerationClicked()
{
    if (!isMotorConnected()) {
        QMessageBox::warning(this, "警告", "电机设备未连接");
        return;
    }

    // 获取参数
    double deceleration = m_decelerationSpinBox->value();

    // 设置减速度
    if (!m_motor->SetDeceleration(deceleration)) {
        QMessageBox::critical(this, "错误", "设置减速度失败");
        return;
    }

    showMessage(QString("已设置减速度: %1").arg(deceleration));
}

void Motor_Control_Panel::onSetHomeParameters()
{
    if (!isMotorConnected()) {
        QMessageBox::warning(this, "警告", "电机设备未连接");
        return;
    }

    // 获取参数
    double homeSpeed = m_homeSpeedSpinBox->value();
    double homeAccDec = m_homeAccDecSpinBox->value();
    double homeFallStep = m_homeFallStepSpinBox->value();

    // 对于简化版FuYu电机，参数会在调用GoHome时直接传递
    // 这里只是显示已经设置的参数值
    showMessage(QString("已设置回零参数: 速度=%1, 加减速=%2, 落脚步长=%3").arg(homeSpeed).arg(homeAccDec).arg(homeFallStep));
}

double Motor_Control_Panel::calculateMoveTime(double distance, double speed, double acceleration, double deceleration) {
    distance = qAbs(distance);
    double accelTime = speed / acceleration;
    double decelTime = speed / deceleration;
    double accelDistance = 0.5 * acceleration * accelTime * accelTime;
    double decelDistance = 0.5 * deceleration * decelTime * decelTime;
    double totalTime = 0.0;

    if (accelDistance + decelDistance <= distance) {
        double constantSpeedDistance = distance - accelDistance - decelDistance;
        double constantSpeedTime = constantSpeedDistance / speed;
        totalTime = accelTime + constantSpeedTime + decelTime;
    } else {
        double maxReachableSpeed = sqrt(2 * distance * acceleration * deceleration / (acceleration + deceleration));
        accelTime = maxReachableSpeed / acceleration;
        decelTime = maxReachableSpeed / deceleration;
        totalTime = accelTime + decelTime;
    };
    return totalTime;
}

void Motor_Control_Panel::setBeamQualityFrameRate(int frameRate) {
    m_frameRate = frameRate;
}

bool Motor_Control_Panel::startAutoScanProcess() {
    if (!isMotorConnected()) {
        QMessageBox::warning(this, "警告", "电机设备未连接");
        return false;
    }
    if (m_autoScanState != AutoScanState::Idle) {
        QMessageBox::warning(this, "警告", "扫描流程已在进行中");
        return false;
    }

    m_motor->m_scanData.clear();
    
    qDebug() << "开始电机归零...";
    if (!m_motor->Home(HomeDirection::Negative)) {
        QMessageBox::critical(this, "错误", "启动电机归零失败");
        return false;
    }
    
    m_autoScanState = AutoScanState::Homing;
    return true;
}

void Motor_Control_Panel::stopAutoScanProcess()
{
    qDebug() << "停止自动扫描流程";
    m_autoScanStopped = true;

    // 停止所有定时器
    if (m_scanDataCollectionTimer) {
        m_scanDataCollectionTimer->stop();
    }

    // 停止电机移动
    if (m_motor && m_motor->IsMoving()) {
        m_motor->Stop();
    }

    // 重置状态
    m_autoScanState = AutoScanState::Idle;

    // 通知扫描被停止
    if (m_scanCompletedCallback) {
        m_scanCompletedCallback(false);
    }
}

void Motor_Control_Panel::setWavelength(double wavelength) {
 if (!m_beamQualityAnalysis) {
     m_beamQualityAnalysis->setWavelength(wavelength);
 }
}


bool Motor_Control_Panel::calculateAutoBeamQualityPositions() {
    // 检查连接状态
    if (!isMotorConnected()) {
        qWarning() << "电机设备未连接";
        return false;
    }

    // 安全检查扫描数据
    if (m_motor->m_scanData.isEmpty()) {
        qWarning() << "没有扫描数据可用，需要先执行扫描";
        return false;
    }

    try {

        QVector<ScanDataPoint> safeScanData = m_motor->m_scanData;

        int size=safeScanData.size();
        for (int i = 0; i < size; i++) {
            qDebug() << "safeScanData[" << i << "].position: " << safeScanData[i].position;
        };

        BeamQualityMeasurementResults beamQualityResults = m_beamQualityAnalysis->calculateFullResults(safeScanData, m_scanConfig);
        
        if (beamQualityResults.measurementPositions.isEmpty()) {
            qWarning() << "无法计算有效的测量位置";
            return false;
        }

        // 将计算出的位置存储到预设位置中
        m_presetPositions.clear();
        for (double pos : beamQualityResults.measurementPositions) {
            m_presetPositions.append(pos);
        }
        updatePresetListDisplay();

        qDebug() << "计算出" << m_presetPositions.size() << "个测量位置:" << m_presetPositions;
        return true;
    } catch (const std::exception& e) {
        qWarning() << "计算测量位置时出错:" << e.what();
        return false;
    }
}

void Motor_Control_Panel::disableUnsupportedFeatures() {
    // 禁用插补控制功能
    m_x2AxisSpinBox->setEnabled(false);
    m_y2AxisSpinBox->setEnabled(false);
    m_x3AxisSpinBox->setEnabled(false);
    m_y3AxisSpinBox->setEnabled(false);
    m_z3AxisSpinBox->setEnabled(false);
    m_xArcSpinBox->setEnabled(false);
    m_yArcSpinBox->setEnabled(false);
    m_angleArcSpinBox->setEnabled(false);
    m_linearInterpolation2AxisButton->setEnabled(false);
    m_linearInterpolation3AxisButton->setEnabled(false);
    m_arcInterpolationButton->setEnabled(false);
    m_stopInterpolationButton->setEnabled(false);
    
    // 禁用IO控制功能
    m_outputPortSpinBox->setEnabled(false);
    m_outputValueSpinBox->setEnabled(false);
    m_inputPortSpinBox->setEnabled(false);
    m_setOutputButton->setEnabled(false);
    m_getInputButton->setEnabled(false);
    
    // 禁用485通信功能
    m_write485DataEdit->setEnabled(false);
    m_read485DataEdit->setEnabled(false);
    m_write485DataButton->setEnabled(false);
    m_read485DataButton->setEnabled(false);
    
    // 显示警告信息
    m_inputValueLabel->setText("不支持");
    m_read485DataEdit->setText("不支持的功能");
    
    showMessage("当前电机不支持插补、IO和485通信功能");
}

// 状态监控方法实现
void Motor_Control_Panel::startStatusMonitoring() {
    if (m_statusMonitorTimer && !m_statusMonitorTimer->isActive()) {
        m_lastMotorStatus = MotorStatus::Disconnected;
        m_statusMonitorTimer->start();
        qDebug() << "开始状态监控";
    }
}

void Motor_Control_Panel::stopStatusMonitoring() {
    if (m_statusMonitorTimer) {
        m_statusMonitorTimer->stop();
        qDebug() << "停止状态监控";
    }
}

void Motor_Control_Panel::onStatusMonitorTimer()
{
    updateStatus(); // Does the regular UI update

    if (m_autoScanState == AutoScanState::Idle) {
        return;
    }

    // IsMoving() also updates the internal motor status based on hardware query
    bool isMoving = m_motor->IsMoving();

    if (m_autoScanStopped) {
        m_autoScanState = AutoScanState::Idle;
        m_autoScanStopped = false;
        return;
    }

    if (m_autoScanState == AutoScanState::Homing) {
        if (!isMoving) {
            // Homing seems to be finished
            qDebug() << "电机归零完成，开始扫描移动";
            m_autoScanState = AutoScanState::Scanning;
            m_scanDataCollectionTimer->start(static_cast<int>(m_motor->scantimer));

            double maxPosition = m_coordinateStrategy->getMaxPosition();
            if (!m_motor->MoveTo(maxPosition, MotionMode::Absolute)) {
                qWarning() << "启动扫描移动失败";
                m_scanDataCollectionTimer->stop();
                m_autoScanState = AutoScanState::Idle;
                // emit autoScanCompleted(false);
                if (m_scanCompletedCallback) {
                    m_scanCompletedCallback(false);
                }
            }
        }
    }
    else if (m_autoScanState == AutoScanState::Scanning) {
        if (!isMoving) {
            // Scanning move is finished
            qDebug() << "扫描移动完成，采集到" << m_motor->m_scanData.size() << "个数据点";
            m_scanDataCollectionTimer->stop();
            m_autoScanState = AutoScanState::Idle; // Reset state for the next run
            /*qDebug() << "receivers =" << this->receivers(SIGNAL(autoScanCompleted(bool)));
            qDebug() << "emit from MCP =" << this;
            emit autoScanCompleted(true);*/
            if (m_scanCompletedCallback) {
                qDebug() << "Calling scan completed callback...";
                m_scanCompletedCallback(true);
            }
        }
    }
}

void Motor_Control_Panel::onScanDataCollection() {
    if (!isMotorConnected()) {
        m_scanDataCollectionTimer->stop();
        m_autoScanState = AutoScanState::Idle;
        // emit autoScanCompleted(false);
        if (m_scanCompletedCallback) {
            m_scanCompletedCallback(false);
        }
        return;
    }
    
    // 采集当前位置和光束宽度数据
    double internalPos = m_motor->GetPosition();
    double externalPos = m_coordinateStrategy->internalToExternal(internalPos);
    
    // 从RayCi系统获取当前的主轴宽度数据
    double majorBeamWidth = 0.0;
    double minorBeamWidth = 0.0;
    if (liveModeAnalysis) {
        // We assume the desired beam width is from the 2nd Moments analysis result.
        // This call fetches the most recent result calculated by LiveMode_Analysis's thread.
        majorBeamWidth = liveModeAnalysis->getSecondMomentResult().dMajor;
        minorBeamWidth = liveModeAnalysis->getSecondMomentResult().dMinor;
    }

    ScanDataPoint dataPoint;
    dataPoint.position = externalPos;
    dataPoint.beamWidthX = majorBeamWidth; // Store major axis width in X
    dataPoint.beamWidthY = minorBeamWidth; // Store it in Y as well, since the analysis function uses both X and Y widths.
    dataPoint.intensity = 0; // Intensity is not used in the analysis function.
    dataPoint.timestamp = QDateTime::currentDateTime();

    // 只有当光束宽度数据有效时才记录
    if (dataPoint.beamWidthX > 0) {
        m_motor->m_scanData.append(dataPoint);
    }
}

// 配置位置按钮点击事件
void Motor_Control_Panel::onConfigurePositionClicked()
{
    PositionConfigDialog dialog(this);
    dialog.setPositions(m_presetPositions);
    
    if (dialog.exec() == QDialog::Accepted) {
        m_presetPositions = dialog.getPositions();
        updatePresetListDisplay();
        showMessage(QString("已更新 %1 个预设位置").arg(m_presetPositions.size()));
    }
}

// 移动到预设位置
void Motor_Control_Panel::onMoveToPresetClicked()
{
    QListWidgetItem *currentItem = m_presetListWidget->currentItem();
    if (!currentItem) {
        QMessageBox::warning(this, "警告", "请先选择一个预设位置");
        return;
    }
    
    int index = currentItem->data(Qt::UserRole).toInt();
    if (index >= 0 && index < m_presetPositions.size()) {
        double position = m_presetPositions[index];
        MoveAbsolute(position);
        
        // 使用配置类验证光路位置有效性
        MotorConfig* config = MotorConfig::getInstance();
        bool isMeasurement = m_measurementModeCheckBox->isChecked();
        if (config->isValidOpticalPathPosition(position)) {
            emit positionChanged(position, isMeasurement);
        }
        
        if (isMeasurement) {
            bool isRecording = true;
            while (isRecording) {
                RayCi_BeamQuality_Recording_isRecording(_nBeamQualityDocId, &isRecording);
            }
        }
        
        showMessage(QString("正在移动到位置: %1").arg(position));
    }
}

// 顺序移动所有位置
void Motor_Control_Panel::onSequentialMoveClicked()
{
    if (m_presetPositions.isEmpty()) {
        QMessageBox::information(this, "提示", "预设位置列表为空");
        return;
    }
    
    if (m_isSequentialMoving) {
        QMessageBox::information(this, "提示", "正在执行顺序移动，请等待完成");
        return;
    }
    
    m_isSequentialMoving = true;
    m_currentPresetIndex = 0;
    m_sequentialMoveButton->setText("🛑 停止移动");
    m_sequentialMoveButton->setEnabled(true);
    
    // 开始第一个位置的移动
    onSequentialMoveTimer();
}

// 顺序移动定时器
void Motor_Control_Panel::onSequentialMoveTimer()
{
    if (!m_isSequentialMoving || m_currentPresetIndex >= m_presetPositions.size()) {
        // 完成所有移动
        m_isSequentialMoving = false;
        m_sequentialMoveButton->setText("🔄 顺序移动");
        QMessageBox::information(this, "完成", "所有移动完成");
        return;
    }
    
    double position = m_presetPositions[m_currentPresetIndex];
    MoveAbsolute(position);
    
    // 使用配置类验证光路位置有效性
    MotorConfig* config = MotorConfig::getInstance();
    bool isMeasurement = m_measurementModeCheckBox->isChecked();
    if (config->isValidOpticalPathPosition(position)) {
        emit positionChanged(position, isMeasurement);
    }
    
    if (isMeasurement) {
        bool isRecording = true;
        while (isRecording) {
            RayCi_BeamQuality_Recording_isRecording(_nBeamQualityDocId, &isRecording);
        }
    }
    
    showMessage(QString("顺序移动: 第 %1/%2 个位置 (%3)")
               .arg(m_currentPresetIndex + 1)
               .arg(m_presetPositions.size())
               .arg(position));
    
    m_currentPresetIndex++;
    
    // 设置1秒后移动到下一个位置
    QTimer::singleShot(1000, this, &Motor_Control_Panel::onSequentialMoveTimer);
}

// 预设位置选择变化
void Motor_Control_Panel::onPresetSelectionChanged()
{
    bool hasSelection = m_presetListWidget->currentItem() != nullptr;
    m_moveToPresetButton->setEnabled(hasSelection && isMotorConnected());
}

// 双击预设位置
void Motor_Control_Panel::onPresetDoubleClicked(QListWidgetItem *item)
{
    if (item && isMotorConnected()) {
        onMoveToPresetClicked();
    }
}

// 更新预设位置列表显示
void Motor_Control_Panel::updatePresetListDisplay()
{
    m_presetListWidget->clear();
    
    for (int i = 0; i < m_presetPositions.size(); ++i) {
        QString itemText = QString("位置 %1: %2 mm").arg(i + 1).arg(m_presetPositions[i], 0, 'f', 3);
        QListWidgetItem *item = new QListWidgetItem(itemText);
        item->setData(Qt::UserRole, i);
        m_presetListWidget->addItem(item);
    }
    
    bool hasPositions = !m_presetPositions.isEmpty();
    m_sequentialMoveButton->setEnabled(hasPositions && isMotorConnected());
}

QList<double> Motor_Control_Panel::getPresetPositions() const
{
    return m_presetPositions.toList();
}